<?php
/**
 * Created by PhpStorm.
 * User: mars
 * Date: 2019/2/4
 * Time: 2:22 AM
 */

namespace api\models;


use api\models\event\MissionEvent;
use common\helpers\Util;
use common\models\Goods;
use phpDocumentor\Reflection\Types\Self_;
use yii\web\ServerErrorHttpException;

class Mission extends \common\models\Mission
{

    public $order_id;

    public function init()
    {
        //监听任务发布事件
        $this->on(self::EVENT_AFTER_POST, [self::className(), 'afterPostHandler']);
        parent::init();
    }

    public function fields()
    {
        return [
            'id',
            'uid',
            'personal_cer'      => function ($model) {
                /**
                 * @var Mission $model
                 */
                return $model->u->getPersonCer();
            },
            'business_cer'      => function ($model) {
                /**
                 * @var Mission $model
                 */
                return $model->u->getBusinessCer();
            },
            'type',
            'is_sign_up'        => function ($model) {
                /**
                 * @var PartTimeJob $model
                 */
                return $model->isSignUp();
            },
            'hide',
            'status'            => function ($model) {
                /**
                 * @var PartTimeJob $model
                 */
                if ($model->isSignUp()) {
                    return 1; //已报名
                }
//                var_dump(time());
//                var_dump($model->end_at);
//                var_dump(strtotime($model->end_at));
                if (time() > $model->end_at) {
//                    return ['time'=>\Yii::$app->formatter->asDate(time()),'end_at'=>$model->end_at,'status'=>2];
                    return 2; //已结束
                }
                return 0; //未领取
            },
            'title',
            'order_id'          => function ($model) {
                return $model->order_id;
            },
            'mission_type',
            'mission_type_name' => function ($model) {
                return JobType::findOne($model->mission_type)->name;
            },
            'content',
            'contact_name',
            'contact_phone',
            'latitude',
            'longitude',
            'ad_code',
            'location'          => function ($model) {
                return Util::getLocationByAdCode((int)$model->ad_code);
            },
            'start_at'          => function ($model) {
                return \Yii::$app->formatter->asDate($model->start_at);
            },
            'end_at'            => function ($model) {
                return \Yii::$app->formatter->asDate($model->end_at);
            },
            'work_start',
            'work_end',
            'salary',
            'gender_needed',
            'pay_type',
            'created_at'        => function ($model) {
                return \Yii::$app->formatter->asDatetime($model->created_at);
            },
        ];
    }

    public function rules()
    {
        return [
//            [['uid', 'type'], 'required'],
//            [['pay_needed'], 'required'],
            [
                [
//                    'uid',
//                    'type',
                    'status',
                    'forbidden',
                    'pay_needed',
                    'created_at',
                    'updated_at',
                    'mission_type',
                    'gender_needed',
                    'salary',
                    'pay_type',
                    'hide',
                ],
                'integer'
            ],
            [
                [
                    'content',
                    'start_at',
                    'end_at',
                ],
                'string'
            ],
            [
                [
                    'title',
                    'contact_name',
                    'contact_phone',
                    'latitude',
                    'longitude',
                    'ad_code',
                ],
                'string',
                'max' => 255
            ],
            [
                ['uid'],
                'exist',
                'skipOnError'     => true,
                'targetClass'     => User::className(),
                'targetAttribute' => ['uid' => 'id']
            ],
            [['work_start', 'work_end'], 'safe'],
            ['end_at', 'validateEndTime'],
            ['work_end', 'validateWorkTime'],
        ];
    }


    public function validateEndTime($attribute, $params)
    {
        if ( ! $this->hasErrors()) {
            if ($this->start_at > $this->end_at) {
                $this->addError($attribute, '结束时间不能早于开始时间');
            }
        }
    }

    public function validateWorkTime($attribute, $params)
    {
        if ( ! $this->hasErrors()) {
            if (strtotime($this->work_start) > strtotime($this->work_end)) {
                $this->addError($attribute, '下班时间不能早于上班时间');
            }
        }
    }

    public function isSignUp()
    {
        if (JobRecord::findOne(['jid' => $this->id, 'uid' => \Yii::$app->getUser()->id])) {
            return true;
        }

        return false;
    }

    public function afterFind()
    {
        $this->username = $this->u->username;
//        $this->created_at = date('Y-m-d H:i:s', $this->created_at);
//        $this->updated_at = date('Y-m-d H:i:s', $this->updated_at);
        parent::afterFind();
    }


    /**
     * @return Order|null
     * @throws ServerErrorHttpException
     */
    public function generateOrder()
    {
        $order         = new Order();
        $order->status = Order::STATUS_NOT_PAY;
        $good          = Goods::findByCode("mission_post");
        if ($good == null) {
            throw new ServerErrorHttpException("发布失败");
        }
        $order->good_id = $good->id;
        $order->type    = Order::TYPE_MISSION_POST;
        $order->uid     = \Yii::$app->getUser()->id;
        if ($order->save(false)) {
            return $order;
        } else {
            return null;
        }


    }

    public function beforeSave($insert)
    {
        if ($insert) {
            $this->created_at = $this->updated_at = time();
            $this->forbidden  = Mission::FORBIDDEN;
            $this->uid        = \Yii::$app->getUser()->id;
            $this->type       = self::MISSION_TYPE;
            $this->status     = Mission::NOT_PAY_STATUS;
            $this->hide       = self::ACCESS;
//            $order = new Order();
//            $this->order_id = $this->generateOrder()->order_id;
//            $order->order_id = $this->order_id;
//            $order->save(false);
            if (empty($this->view_num)) { //初始化view_num
                $this->view_num = 5;
            }
        } else {
            $this->created_at = time();
        }

        return parent::beforeSave($insert);
    }

    public function afterSave($insert, $changedAttributes)
    {
        $info = new JobInfo();
        if ($insert) {
            $info->jid = $this->id;
            \Yii::warning($this->id);
            $this->order_id = Order::generateOrderByGoodId(Good::findOne(['code' => "mission_post"])->id,
                Order::TYPE_MISSION_POST, 1, uniqid(), $this->id)->order_id;
//            try {
//            } catch (ServerErrorHttpException $e) {
//                throw new ServerErrorHttpException("订单生成失败");
//            }
        } else {
            $info = JobInfo::findOne(['jid' => $this->id]);
            if (empty($info)) {
                $info      = new JobInfo();
                $info->jid = $this->id;
            }
        }
        $info->mission_type = empty($this->mission_type) ? null : $this->mission_type;
        $info->latitude     = $this->latitude;
        $info->longitude    = $this->longitude;
        $info->ad_code       = $this->ad_code;
        $info->gender_needed = $this->gender_needed;
        $info->start_at      = $this->start_at;
        $info->end_at        = $this->end_at;
        $info->work_end      = $this->work_end;
        $info->work_start    = $this->work_start;
        $info->salary        = $this->salary;
        if (isset($this->salary_type)) {
            $info->salary_type = $this->salary_type;
        }
        $info->pay_typed = $this->pay_type;
        $info->save(false);

        //触发发布事件 当status状态更改为支付成功时触发
//        var_dump($changedAttributes['status']);
//        var_dump($this->status);
        \Yii::warning($changedAttributes['status']);
        \Yii::warning($this->status);
        if ($changedAttributes['status'] != Order::STATUS_PAY_SUCCESS && $this->status == Order::STATUS_PAY_SUCCESS) {
            $event          = new MissionEvent();
            $event->mission = $this;
            \Yii::warning("trigger mission after post");
            $this->trigger($event);
        }
        parent::afterSave($insert, $changedAttributes);
    }


}